<?php
/*
 * @Descripttion: 
 * @Version: 1.0
 * @Author: wangph
 * @Date: 2021-03-31 09:46:02
 * @LastEditors: wangph
 * @LastEditTime: 2021-04-23 10:46:48
 */
// +----------------------------------------------------------------------
// | LwwanPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.lwwan.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 星辰工作室 QQ群331378225
// +----------------------------------------------------------------------
namespace app\order\model;

use app\common\model\Order;
use app\goods\model\Goods;
use app\goods\model\GoodsSku;
use think\Model as ThinkModel;

/**
 * 订单附加信息表
 * @package app\order\model
 */
class OrderInfo extends ThinkModel
{

    // 设置当前模型对应的完整数据表名称
    protected $table = '__ORDER_GOODS_INFO__';

    // 自动写入时间戳
    protected $autoWriteTimestamp = false;

    /**
     * 获取一个订单详情
     * @param null $order_sn
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/10/28 11:32
     */
    public static function get_order_detail($order_sn = null)
    {
        $info = Order::alias('o')->leftJoin('order_goods_info oi', 'o.order_sn = oi.order_sn')->where('o.order_sn', $order_sn)->find();
        //自提类型运费为0
        if ($info['send_type'] == 1) {
            $info['express_price'] = 0;
        }

        $info['order_sn'] = $order_sn;
        /*        $goods_id = OrderRefund::where(["order_sn"=>$order_sn])->column("goods_id");
                $goods_ids = implode(',',$goods_id);
                $where[] = ['goods_id','in',$goods_ids];*/
        $where[] = ['order_sn', '=', $order_sn];
        $order_goods = OrderGoods::where($where)->select();
        if ($order_goods) {
            foreach ($order_goods as $k => $v) {
                if ($v['is_pure_integral'] == 1) {
                    //纯积分兑换
                    $order_goods[$k]['goods_money'] = $v['sales_integral'] . "积分";

                } else {
                    if ($v['sales_integral'] > 0) {

                        //积分+余额兑换
                        $order_goods[$k]['goods_money'] = "¥" . $info['payable_money'] . "+" . $info['cost_integral'] . "积分";
                    }
                }
                $order_goods[$k]['goods_thumb'] = get_file_url($v['goods_thumb']);
                if ($v['sku_id']) {
                    $order_goods[$k]['goods_sn'] = GoodsSku::where("sku_id", $v['sku_id'])->value("sku_sn");
                } else {
                    $order_goods[$k]['goods_sn'] = Goods::where("id", $v['goods_id'])->value("sn");
                }
            }
        }
        $info['order_goods'] = $order_goods;
        return $info;
    }
      /**
     * 修改地址
     * @author 晓风 
     * @param string $order_sn
     * @param int $address_id
     * @param int $user_id
     * @throws \Exception
     */
    public static function editAddressId(string $order_sn,array $address_id , int $user_id = 0){
        
        $map[] =  ["order_sn","=",$order_sn];        
        if($user_id){
            $map[] =  ["user_id","=",$user_id];       
        }
        $order = Order::where($map)->find();
        if(!$order){
            throw new \Exception('你无法修改此地址');
        }   
        if(!in_array($order["status"],[0,1])){
            throw new \Exception('状态已变更，无法修改地址');
        }      
        $info = self::where("order_sn",$order_sn)->find();
        if(!$info){
            throw new \Exception('你无法修改此地址');
        }
        if($info['address_edit']){
            throw new \Exception('地址已修改，无法再次修改');
        }     
        $map1[] =  ["address_id","=",$address_id];        
        if($user_id){
            $map1[] =  ["user_id","=",$user_id];       
        }
        $userAddress = \app\user\model\Address::where($map1)->find();
        if(!$userAddress){
            throw new \Exception('地址选择错误');
        }
        $data = [
            "address_id" => $userAddress['address_id'],
            "receiver_mobile" => $userAddress['mobile'],
            "receiver_address" => $userAddress['address'],
            "receiver_name" => $userAddress['name'],
            "province" => $userAddress['province'],
            "city" => $userAddress['city'],
            "district" => $userAddress['district'],
            "address_edit"=>1
        ];
        $res = self::where("order_sn",$order_sn)->update($data);
        if(!$res){
            throw new \Exception('地址修改失败');
        }          
        $action = '用户修改订单地址';
        OrderAction::addLog($order["order_sn"] , $action , $order["status"]);        
        $address = $data["receiver_name"] .'，'. $data["receiver_mobile"] .'，'. $data["province"] .$data["city"] .$data["district"] .$data["receiver_address"];        
        $thumb = OrderGoods::where("order_sn",$order["order_sn"])->value("goods_thumb");
        \app\operation\model\SystemMessage::create([
            "to_user_id"=> $order['user_id'], 
            "title"=>'您的订单已修改地址',
            "order_sn"=>$order['order_sn'],
            "content"=> "您的商品订单：". $order["order_sn"] 
               . ", 已更改收货地址。"
               . "\n新的地址是：".$address,        
            "msg_type"=>2,               
            "thumb"=>$thumb ?:0 ,
            "custom"=>json_encode(['type'=>'order','id'=> $order['order_sn']]),
            "is_system"=> $user_id ? 0 : 1
        ]);      
        return true;  
        
    }
    
    /**
     * 修改地址
     * @author 晓风
     * 两端修改地址，故合并到模型
     * @param string $order_sn
     * @param array $param
     * @param int $store_id
     * @throws \Exception
     */
    public static function editAddress(string $order_sn,array $param){
        
        $map[] =  ["order_sn","=",$order_sn];   
     
        $order = Order::where($map)->find();
        if(!$order){
            throw new \Exception('你无法修改此地址');
        }   
        if(!in_array($order["status"],[0,1])){
            throw new \Exception('状态已变更，无法修改地址');
        }      
        $info = self::where("order_sn",$order_sn)->find();
        if(!$info){
            throw new \Exception('你无法修改此地址');
        }
        if($info['address_edit']){
            throw new \Exception('地址已修改，无法再次修改');
        }
        $data = [
           "province"=> $param['province'] ??  "",
           "city"=> $param['city'] ??  "",
           "district"=> $param['district'] ??  "",
           "receiver_name"=> $param['receiver_name'] ??  "",
           "receiver_mobile"=> $param['receiver_mobile'] ??  "",
           "receiver_address"=> $param['receiver_address'] ??  "",
           "address_edit"=>1
       ];     
       if(!empty($param['district_id']) ){
           $area = \app\common\model\Area::getParents($param['district_id']);
           if(!$area || count($area) != 3){
               throw new \Exception('省市区设置错误');
           }
           $data["province"] = $area[0]["name"];
           $data["city"] = $area[1]["name"];
           $data["district"] = $area[2]["name"];
       }         
 
        // 验证
        $validate = \think\facade\App::instance()->validate(\app\order\validate\Address::class);
        if(!$validate->check($data)){
            throw new \Exception($validate->getError());
        }
        
        $res = self::where("order_sn",$order_sn)->update($data);
        if(!$res){
            throw new \Exception('地址修改失败');
        }
        
        $action = '平台修改订单地址';
        OrderAction::addLog($order["order_sn"] , $action , $order["status"]);        
        $address = $data["receiver_name"] .'，'. $data["receiver_mobile"] .'，'. $data["province"] .$data["city"] .$data["district"] .$data["receiver_address"];
        
        $thumb = OrderGoods::where("order_sn",$order["order_sn"])->value("goods_thumb");
        \app\operation\model\SystemMessage::create([
            "to_user_id"=> $order['user_id'], 
            "title"=>'您的订单已修改地址',
            "order_sn"=>$order['order_sn'],
            "content"=> "您的商品订单：". $order["order_sn"] 
               . ", 已由平台更改收货地址。"
               . "\n新的地址是：".$address
               . "\n请确认更改收货地址前经过您的协商，如有问题，请及时联系平台处理。",        
            "msg_type"=>2,               
            "thumb"=>$thumb ?:0 ,
            "custom"=>json_encode(['type'=>'order','id'=> $order['order_sn']])
        ]);      
        return true;  
    }
}